#coding=utf-8

import math
import array
import csv
import sys
import operator
import os

def checkfloats(fbin):
    for i in range(3):
        if not((abs(fbin[i]) > 1e-10) and (abs(fbin[i]) < 1e6)): return False
	
    return True;

def parser(fn):
    data = []
    
    fraw = open(fn) 

    filesize= os.path.getsize(fn)

    bsize = 14
    offset = filesize - (int(filesize/bsize) -1)*bsize

    #header
    bin = array.array('B')

    bin = array.array('B')
    bin.fromfile(fraw, offset)   			
    #
    
    fbin = array.array('f')
    fbin.fromfile(fraw, 3)

    bin = array.array('H')
    bin.fromfile(fraw, 1)

    count = 0;
    while(True):
    	if checkfloats(fbin):

            r = []
            fbin.byteswap()

            for j in range(3):
                r.append(str(fbin[j]))
			
            bin.byteswap()
            red = (bin[0] >> 11) & 0x1f
            green = (bin[0] >> 5)  & 0x3f
            blue =  (bin[0] >> 0)  & 0x1f
            r.extend([str(red), str(green), str(blue)])
            data.append(r)
        
    	fbin = array.array('f')

    	try:
    		fbin.fromfile(fraw, 3)
    	except: 
    		break

    	bin = array.array('H')
    	bin.fromfile(fraw, 1)

    	count = count+1
    
    return data

if __name__ == "__main__":
    outfile = './data.txt'
    o = open(outfile, 'w')
    
    dn = sys.argv[1]
    fs = os.listdir(dn)
    fs2 = []
    
    for f in fs:
        if f.endswith('bin'):
            fs2.append(f)
    #print len(fs)
    fs.sort()
    #print fs
    for f in fs2:
        fn = os.path.join(dn, f)
        data = parser(fn)
        
        for d in data:
            s = '\t'.join(d)
            s = s + '\r\n'
        
            o.write(s)
            o.flush()
    o.close()
        
